<?php
namespace Home\Controller;

/**
 * 预定端订单操作相关接口
 * @modify trainyao 2016-05-03 创建
 */
class OrderController extends ParentController
{

    protected function _initialize()
    {
        // 下单接口自动登录,不需要检查登录
        if (! in_array(ACTION_NAME, array(
            'book',
            'bookVcode',
            'getOrderUserInfo'
        ))) {
            $this->hasRight = parent::isLogin();
            if (empty($this->hasRight)) {
                returnJson(403, 304);
                return;
            }
        }
    }

    /**
     * 提交订单
     * @modify trainyao 2016-05-06 创建
     * @modify trainyao 2016-07-07 修改为房间ID可选
     * @modify wenhui 2017-02-16 同时可以预定多个房间（最多三个）随机生成6位数密码 并发短信
     * @modify zhangzhen 2017-03-13 会员系统
     * @modify wenhui 2017-03-30 把账号同步到钥匙包
     * @modify wenhui 2017-05-26 校验国际电话
     */
    public function book()
    {
        $param = I('post.');
        $userLogic = A('Common/User', 'Logic');
        // 检查是否需要校验验证码,并进行校验(未登录以及微信登录并且未绑定手机号需要校验)
        $isLogin = parent::isLogin();
        $wechatAndNotBindMobile = session(C('AUTH_LOGIN_TYPE')) == USER_OAUTH_TYPE_WECHAT_WEB && empty(session(C('USER_MOBILE')));
        if (empty($isLogin) || $wechatAndNotBindMobile) {
            // 第一个入住人为预订人
            $userParam = array(
                'vcode' => $param['vcode'],
                'areacode' => isset($param['users'][0]['areaCode']) ? $param['users'][0]['areaCode'] : '86',
                'mobile' => $param['users'][0]['mobile'],
                'name' => $param['users'][0]['name'],
                'identity' => isset($param['users'][0]['identity']) ? $param['users'][0]['identity'] : '',
                'idsex' => isset($param['users'][0]['idsex']) ? $param['users'][0]['idsex'] : 1,
                'idnation' => isset($param['users'][0]['idnation']) ? $param['users'][0]['idnation'] : '',
                'idaddress' => isset($param['users'][0]['idaddress']) ? $param['users'][0]['idaddress'] : ''
            );
            $validateRule = array(
                'vcode' => 'notnull,notempty,vcode',
                'areacode' => 'notnull,notempty',
                'mobile' => 'notnull,notempty',
                'name' => 'notnull,notempty,length20',
                'identity' => 'IDCard',
                'idsex' => 'notnull',
                'idnation' => 'notnull',
                'idaddress' => 'notnull'
            );
            
            if (empty($userParam['identity'])) {
                unset($validateRule['identity']);
            }
            
            try {
                \Org\Util\Validate::validate($userParam, $validateRule);
                \Org\Util\Validate::validate($userParam['mobile'], 'globalMobile', array(
                    'globalMobile' => array(
                        'function',
                        'checkGlobalMobile,' . $userParam['areacode'],
                        '403,130,error'
                    )
                ));
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
            
            // 校验验证码,session是否有值,验证码是否已经过期
            $vcodeInSession = session(C('BOOK_LOGIN_VALIDATE_CODE'));
            $vcodeSendTime = session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'));
            $mobileInSession = session(C('BOOK_LOGIN_MOBILE'));
            $mobile = $param['users'][0]['mobile'];
            if (empty($vcodeInSession) || empty($vcodeSendTime) || empty($mobileInSession) || $mobile != $mobileInSession) {
                returnJson(403, 100);
                return;
            }
            if (isOverMinute($vcodeSendTime, C('VALIDATE_CODE_OUTDATE_MINUTE'))) {
                returnJson(403, 201);
                return;
            }
            $vcode = $param['vcode'];
            if ($vcode != $vcodeInSession) {
                returnJson(403, 202);
                return;
            }
            $areaCode = isset($param['users'][0]['areaCode']) ? $param['users'][0]['areaCode'] : '86';
            // 校验成功,进行注册并登录
            $userData = $userLogic->checkUserExist($mobile, $areaCode);
            
            try {
                if (empty($userData)) {
                    $name = $param['users'][0]['name'];
                    $string = chr(mt_rand(97, 122));
                    $password = $string . getRandomNumber(5);
                    $registerResult = $userLogic->register($mobile, $password, $name, $areaCode);
                    // 发短信
                    if ($registerResult != false) {
                        $loginLink = "http://" . MEIZHU_BOOK_HOST . "/Home/BookPage/index?hotel={$param['hotel']}";
                        $loginLink = shortenUrl($loginLink);
                        
                        if ($areaCode == '86') {
                            $smsUtil = new \Org\Util\Sms();
                            $smsSendResult = $smsUtil->sendNotRegBook($mobile, $password, $loginLink);
                        } else {
                            $smsUtil = new \Org\Util\yunPian();
                            $smsSendResult = $smsUtil->yunPianSendNotRegBook($areaCode, $mobile, $password, $loginLink);
                        }
                    }
                    $userData = $userLogic->login($mobile, null, $areaCode);
                    
                    // 把账号同步到钥匙包
                    $userLogic->qrclientRegister($mobile, $name, $areaCode);
                }
                // 自动登录成功,写入session
                session(C('USER_AREACODE'), $userData['areacode']);
                session(C('USER_ID'), $userData['id']);
                session(C('USER_MOBILE'), $userData['mobile']);
                session(C('USER_NAME'), $userData['name']);
                
                // 检查是否微信登录,是否需要绑定,并进行处理
                if ($wechatAndNotBindMobile) {
                    $userLogic->bindUser($userData['id'], session(C('WECHAT_LOGIN_OPEN_ID')), USER_OAUTH_TYPE_WECHAT_WEB);
                }
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
            session(C('BOOK_LOGIN_VALIDATE_CODE'), null);
            session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'), null);
            session(C('BOOK_LOGIN_MOBILE'), null);
        }
        
        $validateRule = array(
            'mobile' => 'notnull,notempty',
            'name' => 'notnull,notempty,length20',
            'identity' => 'IDCard',
            'idsex' => 'notnull',
            'idnation' => 'notnull',
            'idaddress' => 'notnull'
        );
        // 校验手机名称
        foreach ($param['users'] as $key => &$userItem) {
            try {
                $userItem['areaCode'] = isset($userItem['areaCode']) ? $userItem['areaCode'] : '86';
                $userItem['identity'] = isset($userItem['identity']) ? $userItem['identity'] : '';
                $userItem['idsex'] = isset($userItem['idsex']) ? $userItem['idsex'] : 1;
                $userItem['idnation'] = isset($userItem['idnation']) ? $userItem['idnation'] : '';
                $userItem['idaddress'] = isset($userItem['idaddress']) ? $userItem['idaddress'] : '';
                
                if (empty($userItem['identity'])) {
                    unset($validateRule['identity']);
                }
                
                \Org\Util\Validate::validate($userItem, $validateRule);
                \Org\Util\Validate::validate($userItem['mobile'], 'globalMobile', array(
                    'globalMobile' => array(
                        'function',
                        'checkGlobalMobile,' . $userItem['areaCode'],
                        '403,130,error'
                    )
                ));
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
        }
        unset($userItem);

        // 是否有优惠券
        if (isset($param['userGetNo'])) {
            try {
                \Org\Util\Validate::validate($param['userGetNo'], 'notnull,notempty,ucpOrder');
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
        }

        // 把入住人进行注册
        if (is_array($param['users'])) {
            // 是否预定重复
            $bookRoomIds = array_column($param['users'], 'room');
            if (count($bookRoomIds) != count(array_unique($bookRoomIds))) {
                returnJson(403, 403);
                return;
            }
            // 注册
            $result = $userLogic->autoRegister($param['users'], $param['hotel']);
        }
        
        $userId = session(C('USER_ID'));
        // 下单
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'hotel' => $param['hotel'],
            'roomType' => $param['roomType'],
            'orderDate' => $param['startDate'],
            'endDate' => $param['endDate'],
            'userId' => $userId,
            'type' => isset($param['type']) ? $param['type'] : 0
        ); // 是否查询

        
        if (isset($param['users'])) {
            $RPCData['users'] = $param['users'];
        }
        
        // 是否在下单分割时间段之内（是否夜审时间）
        $result = $this->isSplitOrderTime($param['hotel'], $param['startDate']);
        $RPCData['isSplitOrder'] = 0; // 是否夜审订单
        if ($result === true) {
            $RPCData['endDate'] = $param['endDate'] = date('Y-m-d', strtotime('+1 days', strtotime($param['endDate'])));
            $RPCData['isSplitOrder'] = 1;
        }
        
        // 是否同一天
        if ($param['startDate'] == $param['endDate'] && ! isset($param['hour'])) {
            returnJson(403, 700);
            return;
        }
        
        // 钟点房
        if (isset($param['hour'])) {
            // 是否在可选时间内
            if (! in_array($param['hour'], [
                2,
                4,
                6
            ])) {
                returnJson(403, 100);
                return;
            }
            $RPCData['hour'] = $param['hour'];
            $hourRoomInitInfo = D('HourRoomInit')->getInfo($param['hotel']);
            // 检测下单时间
            $bookTime_G = explode(':', $param['startTime'])[0];
            if ($bookTime_G < $hourRoomInitInfo['checkintime'] || $bookTime_G >= $hourRoomInitInfo['checkouttime']) {
                returnJson(403, 405);
                return;
            }
            $RPCData['startTime'] = $param['startTime'];
        }
        if (isset($param['month'])) {
            // 是否在可选时间内
            if (! in_array($param['month'], [
                1,
                2,
                3,
                4,
                5,
                6,
                7
            ])) {
                returnJson(403, 100);
                return;
            }
            $RPCData['month'] = $param['month'];
            $RPCData['endDate'] = $param['endDate'] = date('Y-m-d', strtotime('+' . $param['month'] . 'months', strtotime($param['startDate'])));
        }

        // 是否有优惠券
        $RPCData['userGetNo'] = isset($param['userGetNo']) ? $param['userGetNo'] : null;

        // 是否从钥匙包进入
        $qrclietBook = isset($_COOKIE['qrclient_ali_and_wechat']) ? true : false;
        $RPCData['qrclietBook'] = $qrclietBook;
        // 是否微信浏览器
        $isWechatBrowser = isWechatBrowser();
        $RPCData['isWechatBrowser'] = $isWechatBrowser;

        $RPCData['nights'] = getNight($param['startDate'], $param['endDate']);
        $result = $client->book($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            $data['orderHotel'] = $param['hotel'];
            $data['orderNumber'] = $result['data']['orderNumber'];
            $data['isOffline'] = $result['data']['isOffline'];
            if (isset($result['data']['roomIds'])) {
                $data['roomIds'] = $result['data']['roomIds'];
            }
            
            //获取微信公众号授权参数
            $data['ai'] = C('WECHAT_PUBLIC_ACCOUNT_APPID');
            $data['asc'] = C('WECHAT_PUBLIC_ACCOUNT_SECRET');
            
            $payStatus = D('HotelPayDetail')->getPayStatus($param['hotel']);
            if(($payStatus&32)>0)
            {
                $payInfo = D('HotelPartnerPay')->getInfoByHotelId($param['hotel']);
                if(!empty($payInfo))
                {
                    $data['ai'] = $payInfo['wechatappid'];
                    $data['asc'] = $payInfo['wechatappsecret'];
                }
            }

            // 返回支付开关状态
            $payLogic = A('Common/Pay', 'Logic');
            $payTypeStatus = $payLogic->getPayType($param['hotel'], (int) $payStatus);

            $aliPay = false;
            if ($payTypeStatus['uclbrt_alipay'] || $payTypeStatus['hotel_alipay']) {
                $aliPay = true;
            }
            $wechatPay = false;
            if ($payTypeStatus['uclbrt_wechat'] || $payTypeStatus['hotel_wechat']) {
                $wechatPay = true;
            }

            $data['ali'] = $aliPay ? ENABLE : DISABLE;
            $data['wechat'] = $wechatPay ? ENABLE : DISABLE;
            $data['vipcardpay'] = $payTypeStatus['vipcardpay'] ? ENABLE : DISABLE;

            returnJson(200, 200, $data);
            return;
        }
        if ($result['httpstatus'] == 403) {
            if ($result['status'] == 500) {
                returnJson(403, 402);
                return;
            }
            if ($result['status'] == 404) {
                returnJson(403, 404);
                return;
            }
            if ($result['status'] == 444) {
                returnJson(403, 406, $result['data']);
                return;
            }
            if ($result['status'] == 1214) {
                $string = '';
                $hotelInfo = D('HotelInfo')->getInfoByHotel($param['hotel']);
                $lastString = \Org\Util\LogicStatus::getInfo(403, 703);
                $firstString = \Org\Util\LogicStatus::getInfo(403, 704);
                foreach ($result['data'] as $key => $orderRoomItem) {
                    $string .= $firstString;
                    if ($orderRoomItem['isExistOrderRoom']) {
                        $string .= $orderRoomItem['name'] . \Org\Util\LogicStatus::getInfo(403, 702) . $hotelInfo['checkintime'];
                    } else {
                        $string .= $orderRoomItem['name'] . \Org\Util\LogicStatus::getInfo(403, 701) . $hotelInfo['checkouttime'];
                    }
                    $string .= '。';
                }
                $string .= $lastString;
                
                returnJson(403, 1214, $string);
                return;
            }
            if ($result['status'] == 1215) {
                returnJson(403, 705);
                return;
            }
            if ($result['status'] == 514) {
                returnJson(403, 706);
                return;
            }
        }
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * 发送预定登录验证码
     * @modify trainyao 2016-04-27 创建
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function bookVcode()
    {
        $param = I('post.');
        $areaCode = I('post.areaCode', '86', 'string');
        $verify = $param['verify'];
        if (empty(checkVcode($verify))) {
            returnJson(403, 203);
            return;
        }
        try {
            \Org\Util\Validate::validate($param['mobile'], 'globalMobile', array(
                'globalMobile' => array(
                    'function',
                    'checkGlobalMobile,' . $areaCode,
                    '403,130,error'
                )
            ));
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        
        // 发送短信验证码
        $mobile = $param['mobile'];
        
        // 校验1分钟内是否已经发送过
        $sendTime = session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'));
        if (! empty($sendTime) && ! isOverMinute($sendTime, C('VALIDATE_CODE_RESENT_MINUTE'))) {
            returnJson(403, 200);
            return;
        }
        
        // 生成随机数字发送
        $vcode = getRandomNumber(4);
        if ($areaCode == '86') {
            $smsUtil = new \Org\Util\Sms();
            $smsSendResult = $smsUtil->sendVocode($mobile, $vcode);
        } else {
            $smsUtil = new \Org\Util\yunPian();
            $smsSendResult = $smsUtil->sendVcode($areaCode, $mobile, $vcode);
        }
        
        if (empty($smsSendResult)) {
            returnJson(500, 507);
            return;
        }
        
        $time = time();
        session(C('BOOK_LOGIN_MOBILE'), $mobile);
        session(C('BOOK_LOGIN_VALIDATE_CODE'), $vcode);
        session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'), $time);
        
        returnJson(200, 200);
    }

    /**
     * 获取用户订单列表
     * @modify trainyao 2016-05-10 创建
     */
    public function userItem()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(200, 200, array(
                'order' => array()
            ));
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId,
            'status' => $param['status'],
            'langSet' => LANG_SET
        );
        $result = $client->userItem($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            foreach ($result['data'] as &$orderItem) {
                unset($orderItem['mobile']);
                unset($orderItem['name']);
                $orderItem['startDate'] = substr($orderItem['startDate'], 0, 10);
                $orderItem['endDate'] = substr($orderItem['endDate'], 0, 10);
            }
            unset($orderItem);
            returnJson(200, 200, array(
                'order' => $result['data']
            ));
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * 订单详情接口
     * @modify trainyao 2016-05-10 创建
     * @modify wenhui 2017-02-20 返回多个房间数据
     */
    public function detail()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId,
            'orderNumber' => $param['orderNumber'],
            'langSet' => LANG_SET
        );

        // 是否从钥匙包进入
        $qrclietBook = isset($_COOKIE['qrclient_ali_and_wechat']) ? true : false;
        $RPCData['qrclietBook'] = $qrclietBook;
        // 是否微信浏览器
        $isWechatBrowser = isWechatBrowser();
        $RPCData['isWechatBrowser'] = $isWechatBrowser;

        $result = $client->detail($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            returnJson(200, 200, $result['data']);
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * 用户确认入住
     * @modify trainyao 2016-05-13 创建
     * @modify wenhui 2017-02-20 修改 通过子订单id确认入住 预订人可以办理多房间入住
     */
    public function checkin()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId,
            
            // 'orderNumber' => $param['orderNumber'],
            'orderRoomId' => $param['orderRoomId'],
            'bookPerson' => $param['bookPerson'],
            'bookUserId' => $param['bookUserId']
        );
        $result = $client->checkin($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            returnJson(200, 200, $result['data']);
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * 用户提前退房
     * @modify trainyao 2016-05-13 创建
     * @modify wenhui 2017-02-20 修改 通过子订单id办理退房 预订人可以办理多房间退房
     */
    public function checkout()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId,
            
            // 'orderNumber' => $param['orderNumber'],
            'orderRoomId' => $param['orderRoomId'],
            'bookPerson' => $param['bookPerson'],
            'bookUserId' => $param['bookUserId']
        );
        $result = $client->checkout($RPCData);
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            returnJson(200, 200, $result['data']);
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * 用户取消订单
     * @modify trainyao 2016-05-13 创建
     * @modify wenhui 2017-02-20 只有预定人才能取消订单（全部取消）
     */
    public function cancel()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        $bookPerson = $param['bookPerson'];
        if ($userId == 0 || $bookPerson != $userId) {
            returnJson(403, 100);
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId,
            'orderNumber' => $param['orderNumber']
        );
        $result = $client->cancel($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            returnJson(200, 200, $result['data']);
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * 用户申请退款
     * @modify trainyao 2016-05-13 创建
     * @modify wenhui 2017-02-20 只有预订人才能申请退款
     */
    public function refund()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        $bookPerson = $param['bookPerson'];
        if ($userId == 0 || $bookPerson != $userId) {
            returnJson(403, 100);
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId,
            'orderNumber' => $param['orderNumber'],
            'reason' => $param['reason']
        );
        $result = $client->refund($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            returnJson(200, 200, $result['data']);
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    /**
     * ription 获取身份证数据
     * @modify wenhui 2016-06-19
     */
    public function getOrderUserInfo()
    {
        $param = I('post.');
        
        $validateRule = array(
            'hotel' => 'notnull,notempty',
            'identity' => 'IDCard'
        );
        
        if (empty($param['identity'])) {
            unset($validateRule['identity']);
        }
        
        try {
            \Org\Util\Validate::validate($param, $validateRule);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        
        if (empty($param['identity'])) {
            returnJson(200, 200, array(
                'isBind' => false
            ));
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'hotel' => $param['hotel'],
            'identity' => $param['identity']
        );
        $orderUserInfo = $client->getOrderUserInfo($RPCData);
        // 根据不同情况返回信息
        if (empty($orderUserInfo['data'])) {
            returnJson(200, 200, array(
                'isBind' => false
            ));
            return;
        }
        $orderUserInfo['isBind'] = true;
        
        returnJson(200, 200, $orderUserInfo);
    }

    /**
     * ription 修改订单
     * @modify wenhui 2017-10-10 创建
     */
    public function saveOrder()
    {
        $param = I('post.');
        
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'orderUserId' => 'notnull,notempty,id',
            'name' => 'notnull,notempty,length255',
            'identity' => 'IDCard',
            'idsex' => 'notnull',
            'idnation' => 'notnull,notempty,length255',
            'idaddress' => 'notnull,notempty'
        );
        
        if (empty($param['identity'])) {
            unset($validateRule['identity']);
        }
        
        try {
            \Org\Util\Validate::validate($param, $validateRule);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'orderUserId' => $param['orderUserId'],
            'name' => $param['name'],
            'identity' => $param['identity'],
            'idsex' => $param['idsex'],
            'idnation' => $param['idnation'],
            'idaddress' => $param['idaddress']
        );
        $result = $client->saveOrder($RPCData);
        
        if ($result['httpstatus'] == 200) {
            returnJson(200, 200);
            return;
        }
        
        returnJson(500, 503);
    }

    /**
     * 获取用户订单列表
     * @modify trainyao 2016-05-10 创建
     */
    public function getTotalCharity()
    {
        if (empty($this->hasRight)) {
            return;
        }
        
        $param = I('post.');
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(200, 200, array(
                'totalCharity' => '0.00'
            ));
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('ORDER_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'userId' => $userId
        );
        $result = $client->getTotalCharity($RPCData);
        
        // 根据不同情况返回信息
        if ($result['httpstatus'] == 200) {
            $result['data']['totalCharity'] = number_format($result['data']['totalCharity'], 2, '.', '');
            returnJson(200, 200, $result['data']);
            return;
        }
        
        returnJson(403, 101, $result['httpstatus'] . $result['status'], null, null, $result['info']);
    }

    public function getWechatInfo() {        
        $param = I('post.');     

        //获取微信公众号授权参数
        $data = array();
        $data['ai'] = C('WECHAT_PUBLIC_ACCOUNT_APPID');
        $data['asc'] = C('WECHAT_PUBLIC_ACCOUNT_SECRET');
        
        $payStatus = D('HotelPayDetail')->getPayStatus($param['hotelId']);
        if(($payStatus&32)>0)
        {
            $payInfo = D('HotelPartnerPay')->getInfoByHotelId($param['hotelId']);
            if(!empty($payInfo))
            {
                $data['ai'] = $payInfo['wechatappid'];
                $data['asc'] = $payInfo['wechatappsecret'];
            }
        }
        
        returnJson(200, 200, $data);
    }

    public function addShareUser()
    {        
        $param = I('post.');
        $orderRoomId = I('post.orderRoomId', 0);
        $areaCode = I('post.areaCode', 86);
        $mobile = I('post.mobile', '');
        $name = I('post.name', '');
        $identity = I('post.identity', '');
        $idsex = I('post.idsex', '');
        $idnation = I('post.idnation', '');
        $idaddress = I('post.idaddress', '');

        if($idsex=='男')
        {
            $idsex = 1;
        }
        if($idsex=='女')
        {
            $idsex = 0;
        }
        $idsex = (int)$idsex;
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        $orderRoomInfo = D('OrderRoom')->getInfoById((int)$orderRoomId);
        if (empty($orderRoomInfo)) {
            returnJson(403, 10001, "error");
            return;
        }
        
        $orderInfo = D('OrderInfo')->getInfoById($orderRoomInfo['orderinfo_id']);
        if (empty($orderInfo)) {
            returnJson(403, 10001, "error");
            return;
        }
        if($orderInfo['userlogin_id']!=$userId)
        {
            returnJson(403, 10008, "error");
            return;            
        }
        
        $hotelId = $orderInfo['hotelentity_id'];
        if(empty(D('HotelDetail')->getShareStatus($hotelId)))
        {
            returnJson(403, 10004, "error");
            return;            
        }

        $hotelCheckinUsableModel = D('HotelCheckinUsable');
        $checkinStatus = $hotelCheckinUsableModel->getCheckinStatus($hotelId);
        if(in_array($checkinStatus, array(1,3)) && empty($identity))
        {
            returnJson(403, 10005, "error");
            return; 
        }

        $validateData = array(
            'areacode' => $areaCode,
            'mobile' => $mobile,
            'name' => $name,
        );
        $validateRule = array(
            'areacode' => 'notnull,notempty',
            'mobile' => 'notnull,notempty',
            'name' => 'notnull,notempty,length20',
        );
        if(!empty($identity))
        {
            $validateData['identity'] = $identity;
            $validateRule['identity'] = 'IDCard';
        }
        try {
            \Org\Util\Validate::validate($validateData, $validateRule);
            \Org\Util\Validate::validate($validateData['mobile'], 'globalMobile', array(
                'globalMobile' => array(
                    'function',
                    'checkGlobalMobile,' . $validateData['areacode'],
                    '403,130,error'
                )
            ));
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        
        $userRoomInfo = D('UserRoom')->getOrderUserList($orderRoomId);
        if (empty($userRoomInfo)) {
            returnJson(403, 10001, "error");
            return;
        }
        $startTime = $endTime = 0;
        $startTime = $userRoomInfo[0]['startdate'];
        $endTime = $userRoomInfo[0]['enddate'];
        if(empty($startTime) || empty($endTime))
        {
            returnJson(403, 10001, $userRoomInfo);
            return ;
        }
        $orderUserIds = array_column($userRoomInfo, 'orderuser_id');        
        $orderUserInfos = D('OrderUser')->getListByIds($orderUserIds);
        if (! is_array($orderUserInfos) || count($orderUserInfos) >= 3) {
            returnJson(403, 10003, "error");
            return;
        }
        foreach ($orderUserInfos as $orderUserInfo)
        {
            if($orderUserInfo['mobile']==$mobile && $orderUserInfo['areacode']==$areaCode)
            {
                returnJson(403, 10007, "error");
                return;
            }
        }
        
        $userLogic = A('Common/User', 'Logic');
        $userLogic->autoRegister(array(
            array(
                'areaCode' => $areaCode,
                'mobile' => $mobile,
                'name' => $name
            )
        ), $orderRoomInfo['hotelentity_id']);
        $shareUserInfo = D('UserLogin')->getInfoByMobile($mobile, $areaCode);
        $shareUserId = 0;
        if (! empty($shareUserInfo)) {
            $shareUserId = $shareUserInfo['id'];
        }
        if($shareUserId==$userId)
        {
            returnJson(403, 10006, "error");
            return;
        }
        
        $orderUserId = D('OrderUser')->addInfo(array(
            'orderinfo_id' => $orderRoomInfo['orderinfo_id'],
            'userlogin_id' => $shareUserId,
            'areacode' => $areaCode,
            'mobile' => $mobile,
            'name' => $name,
            'identity' => $identity,
            'idsex' => $idsex,
            'idnation' => $idnation,
            'idaddress' => $idaddress,
            'isshareuser' => 1
        ));
        D('UserRoom')->addInfo(array(
            'userlogin_id' => $shareUserId,
            'orderroom_id' => $orderRoomInfo['id'],
            'orderuser_id' => $orderUserId,
            'roominfo_id' => $orderRoomInfo['roominfo_id'],
            'startdate' => $startTime,
            'enddate' => $endTime,
        ));
        
        // 操作记录
        $orderRecordId = D('OrderRecord')->addInfo(array(
            'orderinfo_id' => $orderRoomInfo['orderinfo_id'],
            'user' => 1,
            'recordfrom' => 2,
            'creator' => $userId
        ));
        D('OrderUserRecord')->addInfo(array(
            'orderrecord_id' => $orderRecordId,
            'areacode' => $areaCode,
            'mobile' => $mobile,
            'name' => $name,
            'identity' => $identity,
            'idsex' => $idsex,
            'idnation' => $idnation,
            'idaddress' => $idaddress,
            'type' => 1
        ));
        // returnJson(200, 200, $orderRoomInfo);
        returnJson(200, 200, array(
            'orderUserId' => $orderUserId,
        ));
    }

    public function getShareUserList()
    {
        $param = I('post.');
        $orderRoomId = $param['orderRoomId'];
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        $orderRoomInfo = D('OrderRoom')->getInfoById($orderRoomId);
        if (empty($orderRoomInfo)) {
            returnJson(403, 10001, "error");
            return;
        }
        
        $userRoomInfo = D('UserRoom')->getOrderUserList($orderRoomId);
        if (empty($userRoomInfo)) {
            returnJson(200, 200, array());
            return;
        }
        $orderUserIds = array_column($userRoomInfo, 'orderuser_id');        
        $orderUserInfos = D('OrderUser')->getListByIds($orderUserIds);
        
        foreach ($orderUserInfos as &$orderUserInfo) {
            if (strlen($orderUserInfo['identity']) >= 14) {
                $orderUserInfo['identity'] = substr_replace($orderUserInfo['identity'], '******', 4, 10);
            }
            unset($orderUserInfo['orderinfo_id']);
            unset($orderUserInfo['userlogin_id']);
            unset($orderUserInfo['idsex']);
            unset($orderUserInfo['idnation']);
            unset($orderUserInfo['idaddress']);
            unset($orderUserInfo['isshareuser']);
            unset($orderUserInfo['isdelete']);
        }
        unset($orderUserInfo);
        
        returnJson(200, 200, $orderUserInfos);
    }

    public function deleteShareUser()
    {
        $param = I('post.');
        $orderUserId = $param['orderUserId'];
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        $orderUserInfo = D('OrderUser')->getInfoById($orderUserId, false);
        if (empty($orderUserInfo)) {
            returnJson(403, 10002, "error");
            return;
        }
        
        $orderInfo = D('OrderInfo')->getInfoById($orderUserInfo['orderinfo_id']);
        if (empty($orderInfo)) {
            returnJson(403, 10001, "error");
            return;
        }
        if($orderInfo['userlogin_id']!=$userId)
        {
            returnJson(403, 10008, "error");
            return;
        }
        
        D('OrderUser')->updateInfo(array(
            'isdelete' => 1
        ), array(
            'id' => $orderUserId
        ));
        D('UserRoom')->updateInfo(array(
            'isdelete' => 1
        ), array(
            'orderuser_id' => $orderUserId
        ));
        
        // 操作记录
        $orderRecordId = D('OrderRecord')->addInfo(array(
            'orderinfo_id' => $orderUserInfo['orderinfo_id'],
            'user' => 1,
            'recordfrom' => 2,
            'creator' => $userId
        ));
        D('OrderUserRecord')->addInfo(array(
            'orderrecord_id' => $orderRecordId,
            'areacode_before' => $orderUserInfo['areacode'],
            'mobile_before' => $orderUserInfo['mobile'],
            'name_before' => $orderUserInfo['name'],
            'identity_before' => $orderUserInfo['identity'],
            'idsex_before' => $orderUserInfo['idsex'],
            'idnation_before' => $orderUserInfo['idnation'],
            'idaddress_before' => $orderUserInfo['idaddress'],
            'type' => 0
        ));
        
        $orderRoomId = D('UserRoom')->where(array('orderuser_id' => $orderUserId))->getField('orderroom_id');

        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('CARD_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'orderRoomId' => $orderRoomId,
            'areaCode' => $orderUserInfo['areacode'],
            'mobile' => $orderUserInfo['mobile'],
        );
        $result = $client->deleteShareCard($RPCData);
        
        if (!is_array($result)) {
            returnJson(500, 500, var_export($result, true));
            return ;
        }
        
        if($result['httpstatus'] != 200)
        {
            returnJson($result['httpstatus'], $result['status'], $result['data'], '', array(), $result['info']);
            return ;
        }
        
        // returnJson(200, 200, $orderUserInfo);
        returnJson(200, 200, 'success');
    }
    
    public function getCardLink()
    {
        $param = I('post.');
        $hotelId = $param['hotelId'];
        $orderRoomId = $param['orderRoomId'];
        $orderUserId = $param['orderUserId'];
        
        $userId = session(C('USER_ID'));
        if ($userId == 0) {
            returnJson(403, 100);
            return;
        }
        
        $orderUserInfo = D('OrderUser')->getInfoById($orderUserId, false);
        if (empty($orderUserInfo)) {
            returnJson(403, 10002, "error");
            return;
        }
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('CARD_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'hotelId' => $hotelId,
            'orderRoomId' => $orderRoomId,
            'areaCode' => $orderUserInfo['areacode'],
            'mobile' => $orderUserInfo['mobile'],
            'operator' => $userId,
        );
        $result = $client->getCardLink($RPCData);
        

        if (!is_array($result)) {
            returnJson(500, 500, var_export($result, true));
            return ;
        }
        
        if($result['httpstatus'] != 200)
        {
            returnJson($result['httpstatus'], $result['status'], $result['data'], '', array(), $result['info']);
            return ;
        }        
        
        $hotelInfo = D('HotelEntity')->getInfo($hotelId);

        $link = empty($result['data'])?'':$result['data'];
        $hotelName = empty($hotelInfo['name'])?'':$hotelInfo['name'];
        
        returnJson(200, 200, array(
            'areaCode' => $orderUserInfo['areacode'],
            'mobile' => $orderUserInfo['mobile'],
            'hotelName' => $hotelName,
            'link' => $link, 
            'content' => sprintf(L('MZ_BOOK_SHARE_CONTENT'), $hotelName, $link),           
        ));
    }
}
